package com.qxzn.app.page.robot;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.R;
import com.qxzn.app.page.R2;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.ActivityStack;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddRobotActivity2 extends BaseActivity {
    @BindView(R2.id.password_input_status_layout)
    LinearLayout statusLayout;
    @BindView(R2.id.tv_prompt)
    TextView tv_prompt;


    StringBuilder password = new StringBuilder();

    @Override
    protected int initLayout() {
        return R.layout.activity_add_robot2;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void iniTitleBar() {
        title_bar.setVisibility(View.GONE);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
    }

    public void onClickCancel(View view) {
        finish();
    }

    public void onClickKeyPad(View view) {
        int id = view.getId();
        if (id == R.id.number_D) {
            if (password.length() > 0) {
                password.delete(password.length() - 1, password.length());
                if (password.length() < statusLayout.getChildCount())
                    statusLayout.getChildAt(password.length()).setSelected(false);
            }
        } else if (password.length() < 6) {
            if (view instanceof TextView) {
                TextView tv = (TextView) view;
                if (password.length() < statusLayout.getChildCount())
                    statusLayout.getChildAt(password.length()).setSelected(true);
                password.append(tv.getText());
                if (password.length() == 6) {
                    bindRobot();
                }
            }
        }
    }

    private void clear() {
        if (password.length() != 0) {
            int lastIndex = password.length();
            for (int i = 0; i < lastIndex; i++) {
                View childAt = statusLayout.getChildAt(i);
                childAt.setSelected(false);
            }
            password.delete(0, password.length());
        }
    }

    private void bindRobot() {
        showProgress();
        JSONObject params = new JSONObject();
        final String robotId = getIntent().getStringExtra(Constant.PutExtraKey.DEVICE_ID);
        final String robotName = getIntent().getStringExtra(AddRobotActivity1.ROBOT_NAME);
        params.put("device_id", robotId);
        params.put("username", SharePreferenceUtil.getUserName(getApplicationContext()));
        params.put("family_password", password.toString());
        HttpRequest.getService().bindingByPassword(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                clear();
                BaseBean body = response.body();
                if (body.getCode() == 200) {
                    tv_prompt.setVisibility(View.GONE);
                    HttpRequest.getService().changeRobot(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
                        @Override
                        public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                            BaseBean baseBean = response.body();
                            hideProgress();
                            if (baseBean != null) {
                                if (baseBean.getCode() == 200) {
                                    SharePreferenceUtil.setDeviceId(AddRobotActivity2.this, robotId);
                                    SharePreferenceUtil.setDeviceName(AddRobotActivity2.this, robotName);
                                    EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.SWITCH_DEVICE_ID).build());
                                    ActivityStack.finishAllWithoutActivity("com.qxzn.app.desktoprobot.MainActivity");
                                    return;
                                }
                            }
                            if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                                ToastUtil.showTextToast(AddRobotActivity2.this, baseBean.getMsg());
                            } else {
                                ToastUtil.showTextToast(AddRobotActivity2.this, "切换失败，请重试");
                            }
                        }

                        @Override
                        public void onFailure(Call<BaseBean> call, Throwable t) {
                            hideProgress();
                            ToastUtil.showTextToast(AddRobotActivity2.this, getString(R.string.network_error));
                        }
                    });
                    return;
                }

                hideProgress();
                tv_prompt.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                clear();
                hideProgress();
                ToastUtil.showTextToast(getApplicationContext(), getString(R.string.network_error));
            }
        });
    }

}
